package com.net.xpay.common;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author  on 23/01/2018.
 */
@Configuration
@MapperScan(basePackages = "com.net.xpay.common.dao", sqlSessionFactoryRef = "xpayCommonSqlSessionFactory")
public class PoseidonCommonDatabaseConfiguration {
    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    @ConfigurationProperties(prefix = "xpay.datasource.common")
    public DataSource xpayCommonDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactoryBean xpayCommonSqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(xpayCommonDataSource());
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class); //必须的，否则spring boot启动的路径不正确
        sqlSessionFactoryBean.setConfigLocation(resourceLoader.getResource("classpath:xpay-common-mybatis.xml"));

        return sqlSessionFactoryBean;
    }

    @Bean
    public DataSourceTransactionManager xpayCommonTransactionManager() {
        return new DataSourceTransactionManager(xpayCommonDataSource());
    }
}
